<template>
  <div class="maina">
    <arrow :topList="topList"></arrow>
    <div class="content">
      <article class="content_box">
        <div class="title_left">内容管理 > 我的素材</div>
        <div class="app-container">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="100px">
            <el-form-item label="关键词：" prop="keyword" style="margin-left: -45px;">
              <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="素材类型：" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择素材类型">
                <el-option v-for="item in keywordList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8" style="margin-left: -23px;">
            <el-col :span="1.5">
              <el-button icon="el-icon-plus" type="primary" size="mini" :visible.sync="open"
                @click="open = true">新增素材</el-button>
              <!-- <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:img:add']"
          >新增</el-button> -->
            </el-col>
            <el-col :span="1.5">
              <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
          @click="handleUpdate">修改</el-button> -->
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                @click="handleDelete">删除</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="info" size="mini" plain icon="el-icon-receiving" @click="mySync">同步</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <el-table stripe v-loading="loading" :data="imgList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="素材ID" type="index" width="100"/>
            <el-table-column label="素材名称" align="center" width="300" prop="materialTitle" >
              <template slot-scope="scope" >
                <div v-if="scope.row.materialTitle && scope.row.materialTitle.length <= 8">{{
                  scope.row.materialTitle }}</div>
                <!-- 大于12为只展示12位 -->
                <el-tooltip style="cursor: pointer;"
                  v-if="scope.row.materialTitle && scope.row.materialTitle.length > 8"
                  popper-class="testtooltip" :content="scope.row.materialTitle" placement="top-start">
                  <div v-if="scope.row.materialTitle">{{ scope.row.materialTitle.slice(0, 8) + '...' }}</div>
                </el-tooltip>
              </template>  
            </el-table-column>
            <el-table-column label="类型" align="center" width="100" prop="type" />
            <el-table-column label="素材用途" align="center" width="300" prop="materialIntroduction" />
            <el-table-column label="分组" align="center" prop="groupName" />
            <el-table-column label="素材上传时间" align="center" prop="createTime">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="素材状态" align="center" prop="status" />
            <el-table-column label="素材来源" align="center" prop="sourceMaterials" />
            <el-table-column align="left" prop="sourceUrl">
              <template slot-scope="scope">
                <div style="width: 125px;padding: 10px;" v-show="false">
                  <el-image :ref="scope.row.materialId" style="width: 100%;" :preview-src-list="[scope.row.sourceUrl]"
                    :src="scope.row.sourceUrl"></el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" align="center" class-name="fixed-width" width="200">
              <template slot-scope="scope">
                <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:img:edit']">修改</el-button> -->
                <el-button icon="el-icon-search" size="small" plain v-if="['视频', '音频', '动漫'].includes(scope.row.type)"
                  @click="openMedia(scope.row)">预览</el-button>
                <el-button icon="el-icon-search" size="small" plain v-if="['图片', '挂图'].includes(scope.row.type)"
                  @click="openImg(scope.row.materialId)">预览</el-button>
                <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="editMySucai(scope.row)">编辑</el-button> -->
                <el-button size="small" plain type="danger" icon="el-icon-delete"
                  @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />


          <!--同步素材 -->
          <el-dialog :title="title" :visible.sync="openAccountList" width="500px" append-to-body center>
            <el-form ref="form" :model="sucaiform" :rules="rules" label-width="140px">
              <el-form-item label="同步账号" prop="account">
                <el-select v-model="sucaiform.account" placeholder="请选择账号">
                  <el-option v-for="item in account" :key="item.accountId" :label="item.name" :value="item.openId">
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="素材类型" prop="type">
                <el-checkbox-group v-model="checkList" :min="1">
                  <el-checkbox label="图片"></el-checkbox>
                  <el-checkbox label="视频"></el-checkbox>
                  <el-checkbox label="音频"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-form>
            <div slot="footer" style="text-align: center;">
              <el-button type="primary" :loading="sucaiLoading" @click="submitForm">同步素材(共计{{ sucaiGetNum }}条)</el-button>
              <!-- <el-button @click="cancel">取 消</el-button> -->
            </div>
          </el-dialog>

          <!-- 视频预览组件 -->
          <videomask :isOpens="isOpens" @updateProps="updateValues" :url="MdediaSourceUrl"></videomask>

          <MyDia :isOnOpen="open" @updateProp="updateValue" @getList="getList"></MyDia>
        </div>
      </article>
    </div>
  </div>
</template>
  
<script>
import { listMaterial, myDel, syncMaterial, myOpenId, sucaiSync, sucaiSyncNum } from "@/api/my";
import { listImg, getImg, delImg, addImg, updateImg } from "@/api/system/img";
import { getToken } from "@/utils/auth";
import MyDia from '@/views/content/addpic'
import videomask from '@/views/content/videomask'
import arrow from '@/views/components/arrow'

export default {
  components: { MyDia, videomask, arrow },
  name: "Img",
  data() {
    return {
      sucaiLoading: false,   //素材加载时按钮出现加载状态
      sucaiGetNum: 0,
      openAccountList: false,
      account: [],  //同步账号列表
      checkList: [],  //选中素材类型
      sucaiform: {  //提交素材表单
        account: '',
        type: ''
      },
      isOpens: false,
      topList: {
        title: '流程指引',
        list: [
          { name: '素材管理', img: 'blue' },
          { name: '内容创作', img: 'gray' },
          { name: '专家审核', img: 'gray' },
          { name: '产品分发', img: 'gray' },
          { name: '传播管理', img: 'gray' },
        ]
      },
      obj: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      imgList: [],
      // 弹出层标题
      title: "同步素材", //同步素材
      // 是否显示弹出层，同步素材
      open: false,
      // 查询参数
      keywordList: [{
        value: 1,
        label: '图片'
      }, {
        value: 2,
        label: '视频'
      }, {
        value: 3,
        label: '音频'
      }, {
        value: 4,
        label: '动漫'
      }, {
        value: 5,
        label: '挂图'
      },
      {
        value: 6,
        label: '缩略图'
      }],
      sucaiLists: [
        {
          value: 1,
          label: '图片'
        }, {
          value: 2,
          label: '视频'
        }, {
          value: 3,
          label: '音频'
        },
      ],
      accountTypeList: [
        { value: 1, label: '微信公号' },
        { value: 2, label: '省平台' },
        { value: 3, label: '终端大屏' },
      ],
      sucaiSource: [
        { value: 1, label: '网络' },
        { value: 2, label: '委托' },
        { value: 3, label: '原创' },
        { value: 4, label: '本地' },
      ],
      sucaiStatus: [
        { value: 0, label: '正常' },
        { value: -1, label: '下架' },
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,      //类型
        keyword: null,  //关键词
        imgUrl: null,
        imgType: null,
        reportWechat: null,
        wechatUrl: null,
        wechatMediaId: null,
        userId: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      fileList: [],
      // 表单校验
      rules: {
        imgName: [
          { required: true, message: "名称不能为空", trigger: "change" }
        ],
      },
      MdediaSourceUrl: '',  //当前播放的音视频Url
      url: "",
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  created() {
    this.url = process.env.VUE_APP_BASE_API + "/system/sourceMaterialImg/sourceMaterialImgUpload"
    this.getList();
    this.getAccount()
  },
  watch: {
    checkList: {  //多选素材发生变化
      handler(ne, ol) {
        // console.log(ne,121212);
        this.myAccountNum()

      },
      deep: true
    },
    'sucaiform.account'(ne, ol) {  //账号发生变化
      this.myAccountNum()

    }
  },
  methods: {
    download(filename, text) {
      var element = document.createElement('a');
      element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
      element.setAttribute('download', filename);

      element.style.display = 'none';
      document.body.appendChild(element);

      element.click();

      document.body.removeChild(element);
    },
    openMedia(row) {  //音视频播放
      // this.isOpens = true
      // this.MdediaSourceUrl = ''
      // this.MdediaSourceUrl = row.sourceUrl
      window.open(row.sourceUrl, '_blank')
      // this.download(row.sourceUrl, '音视频文件');
    },
    async getAccount() {
      let res = await sucaiSync()
      if (res.code == 200) {
        //1、微信公号 2、省平台 3、终端大屏
        this.account = res.rows.map(v => {
          if (v.accountType == 1) {
            v['name'] = v.accountName + `(微信公号)`
          }
          if (v.accountType == 2) {
            v['name'] = v.accountName + `(省平台)`
          }
          if (v.accountType == 3) {
            v['name'] = v.accountName + `(终端大屏)`
          }
          return v
        })
      }
      if (res.rows.length > 0) {
        this.sucaiform.account = res.rows[0].openId
        this.checkList.push('图片')
      }

      //this.checkList.push('视频')
      //this.checkList   
      // this.myAccountNum()
      //  console.log(result);
      // console.log('11111');
    },
    async myAccountNum() { //同步素材数量
      let openId = this.sucaiform.account
      let materialType = this.checkList.reduce((pre, value, index) => {
        let r = this.sucaiLists.find(v => v.label == value)
        if (r !== undefined) pre.push(r.value)
        return pre
      }, [])
      // console.log(materialType);
      this.sucaiLoading = true
      let result = sucaiSyncNum(openId, materialType).then((sp) => {
        this.sucaiLoading = false
        this.sucaiGetNum = sp.data || 0
      }).catch((e) => {
        //  console.log(e,'e');
        // this.$notify.info({ message: '同步素材错误，请稍后尝试' })
        this.sucaiLoading = false
        this.sucaiGetNum = 0
      })
      // console.log(result.code,123);


    },
    // async getImgs() {
    //   let res = await listMaterial()
    // },
    async mySync() { //同步数据
      if (this.account.length < 1) {
        this.$message.info({ title: '提示', message: '请先绑定平台账号' })
        return
      }
      this.openAccountList = true
      // let openidREes = await myOpenId()
      // let getOpenId = openidREes.rows[0].openId
      // let data = { 'materialType': [1], 'openId': getOpenId, 'accountType': 1 }
      // let res = await syncMaterial(data)

      // console.log( openidREes.rows[0].openId,123);
      // return
      // console.log(res, 9111);
    },
    /** 提交按钮。同步素材提交 */
    async submitForm() {
      let res = this.account.find(v => v.openId == this.sucaiform.account)
      let materialType = this.checkList.reduce((pre, value, index) => {
        let r = this.sucaiLists.find(v => v.label == value)
        if (r !== undefined) pre.push(r.value)
        return pre
      }, [])
      // console.log(res);
      if (res !== undefined) {
        let data = { 'materialType': materialType, 'openId': res.openId, 'accountType': res.accountType }
        let result = await syncMaterial(data)
        if (result.code == 200) {
          await this.getList();
          this.openAccountList = false
        }
      }
      // let data = { 'materialType': [1], 'openId': getOpenId, 'accountType': 1 }
      // let res = await syncMaterial(data)

      // this.$refs["form"].validate(valid => {
      //   if (valid) {
      //     if (this.form.imgId != null) {
      //       updateImg(this.form).then(response => {
      //         this.$modal.msgSuccess("修改成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     } else {
      //       addImg(this.form).then(response => {
      //         this.$modal.msgSuccess("新增成功");
      //         this.open = false;
      //         this.getList();
      //       });
      //     }
      //   }
      // });
    },
    openImg(id) {
      // console.log(id);
      this.$refs[id].clickHandler();
    },
    updateValues(val) {
      this.isOpens = val
    },
    handleRemove(file, fileList) {
    },
    handlePreview(file) {
      if (file.code == 500) {
        this.$message.warning(file.msg);
      } else {
        this.getList()
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      listMaterial(this.queryParams).then(response => {
        response.rows.map(v => {
          let typeHandle = this.keywordList.find(name => name.value == v.type)
          if (typeHandle !== undefined) {
            v.type = typeHandle.label
            v.sourceUrl = process.env.VUE_APP_ImgUrlHeader + v.sourceUrl //拼接url
          }

          let sucailaiyuan = this.sucaiSource.find(names => names.value == v.sourceMaterials)
          if (sucailaiyuan !== undefined) {
            v.sourceMaterials = sucailaiyuan.label
          }

          let sucaistatuss = this.sucaiStatus.find(params => params.value == v.status)
          //console.log(sucaistatuss.label,v.status);
          if (sucaistatuss !== undefined) {
            v.status = sucaistatuss.label
          }
          //  console.log(v.sourceUrl );
          return v
        })
        //  console.log(a);
        this.imgList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消同步
    cancel() {
      // this.open = false;
      // this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        imgId: null,
        imgUrl: null,
        imgType: null,
        reportWechat: null,
        wechatUrl: null,
        wechatMediaId: null,
        userId: null,
        isDelete: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.materialId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const imgId = row.imgId || this.ids
      getImg(imgId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const imgIds = row.materialId || row.imgId || this.ids;
      // console.log(row, 'aaa', imgIds);
      // ${row.materialTitle}
      this.$modal.confirm(`是否确认删除？`).then(function () {
        return myDel(imgIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    //编辑
    editMySucai(row) {
      let id = row.materialId
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/img/export', {
        ...this.queryParams
      }, `img_${new Date().getTime()}.xlsx`)
    },
    updateValue(newProp) {
      this.open = newProp;
      this.getList()
    }
  }
};
</script>
  
<style lang='scss' scoped>
.maina {
  background-color: #f5f5f5;

  .content {
    margin-top: 10px;
    background-color: white !important;

    .content_box {
      padding-left: 32px;

      .title_left {

        padding-top: 31px;
        font-size: 16px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 700;
        color: #3D3D3D;
        line-height: 21px;
      }
    }
  }
}
</style>